// pages/start-fighting/start-fighting.js
const httpApi = require("../../http/request"); //后续可以改为你自己的域名接口地址
const setting = require("../../http/env");
let socket = null; //全局定义socket对象
let socketOpen = false; //是否开启websoket
let timer = null;
var app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    //默认域名
    baseUrl: setting.baseUrl,
    //答题比赛id
    quest_game_id: 0,
    //比赛题目id
    game_topic_id: 0,
    //正确答案
    answer_true: "",
    //答案
    answer: "",
    //是否超时
    time_over: 0,

    //房主
    initiate_user: "",
    initiate_user_id: '',
    //匹配人
    match_user: "",
    match_user_id: '',

    //是否回答正确
    is_right: false,
    //答对数量
    right_num: 0,

    //退出提示
    showExitWarn: false,
    //倒计时
    countDown: 20,
    processVal: 0,
    processSpeed: 200,

    //题目列表
    showTopicInfo: {},
    musicVideo: null,

    //答题数量
    all_num:5,
    now_num:0,

    // 书名
    book_name: '',
    showBaseUrl: false,
    showBookName: false,
  },

  //数据回调
  mycallback(data) {
    var start = data.indexOf("["); // 第一次出现的位置
    var start1 = data.indexOf("{");

    if (start < 0) {
      start = start1;
    }
    if (start >= 0 && start1 >= 0) {
      start = Math.min(start, start1);
    }

    if (start >= 0) {
      // console.log(data);
      var json = data.substr(start); //截取
      var json = JSON.parse(json);
      return json;
    } else {
      return "";
    }
  },

  // 上报数据
  send() {
    var that = this;
    if (socketOpen) {
      var param = {
        type: "match",
        data: [
          {
            user_id: that.data.user.id,
            quest_game_id: that.data.quest_game_id,
            game_topic_id: that.data.game_topic_id,
            answer: that.data.answer,
            time_over: that.data.time_over,
          },
        ],
      };
      console.log('上报数据========', param.data);
      socket.send({
        data: JSON.stringify(param),
        success: function (e) {
          console.log(e);
        },
      });
    }
  },

  //接收信息
  geMessage(data) {
    var that = this;
    // 匹配到题目 开始倒计时
    if (data && data[0] == "data") {
      var showTopicInfo = {
        topicName: data[1].name,
        robotWin:data[1].robot_win,
        chooseList: [
          {
            name: data[1].answer_a,
            val: "A",
          },
          {
            name: data[1].answer_b,
            val: "B",
          },
        ],
      };

      if (data[1].answer_c) {
        showTopicInfo.chooseList.push({
          name: data[1].answer_c,
          val: "C",
        });
      } 
      if (data[1].answer_d) {
        showTopicInfo.chooseList.push({
          name: data[1].answer_d,
          val: "D",
        });
      }

      var now_num=that.data.now_num;
      now_num=now_num+1;

      that.setData({
        initiate_user: data[1].initiate_user,
        match_user: data[1].match_user,
        game_topic_id: data[1].id,
        answer_true: data[1].answer_true,
        answer: "",
        time_over: 0,
        showTopicInfo: showTopicInfo,
        is_right: false,
        //倒计时
        countDown: 20,
        processVal: 0,
        processSpeed: 200,

        now_num:now_num,
        book_name: data[1].book_name,
        showBaseUrl: !data[1].initiate_user.headimg.includes('http')
      });

      console.log('clearInterval======')
      clearInterval(timer);
      this.stopVideo();
      that.setCountDown();
    }
    //比赛结束
    if (data && data[0] == "end") {
      wx.redirectTo({
        url: "../result/result?quest_game_id=" + that.data.quest_game_id + '&count=' + data[1].count + '&robot_flag=' + data[1].robot_flag + '&continue_flag=' + data[1].continue_flag,
      });
    }
    //退出比赛
    if (data && data[0] == "outline") {
      if (that.data.answer) {
        //已答题、进入下一题
        that.setData({
          time_over: 1,
        });
        //下一题
        that.send();
      }
    }
  },

  // 定时器
  setCountDown() {
    var that = this;
    var timeCount = that.data.countDown;
    console.log('setInterval======')
    timer = setInterval(() => {
      timeCount--;
      var proValue = (20 - timeCount) * 5;
      that.setData({
        countDown: timeCount,
        processVal: proValue,
      });
      if (timeCount === 5) {
        // 倒计时声音
        this.playVideo();
      }
      if (timeCount <= 0) {
        that.setData({
          time_over: 1,
        });
        // 倒计时结束且没有答题
        if (that.data.answer == "") {
          that.send();
        }

        clearInterval(timer);
        that.stopVideo();
      }
    }, 1000);
  },

  //退出提示
  closeExitWarn() {
    this.setData({
      showExitWarn: false,
    });
  },

  //退出提示
  back() {
    console.log("exit");
    this.setData({
      showExitWarn: true,
    });
  },

  // 答题
  chooseOption(e) {
    var that = this;
    if (!that.data.answer) {
      var answer = e.currentTarget.dataset.item.val;
      var is_right = false;
      var right_num = that.data.right_num;
      if (answer == that.data.answer_true) {
        is_right = true;
        right_num += 1;
      }
      
      that.setData({
        answer: answer,
        is_right: is_right,
        right_num: right_num,
      });

      if(that.data.showTopicInfo.robotWin==1){
        var suiji=Math.floor(Math.random() * 4);
        if(suiji==0){
          suiji=1;
        }
        suiji=suiji*1000;
      }else{
        var suiji=1000;
      }
      

      setTimeout(() => {
        //下一题
        that.send();
      }, suiji);
    }
  },

  // 获取标题名称
  getIndexTt() {
    httpApi
      .Post("/index/getIndexTt", {},'')
      .then((res) => {
        console.log(res);
        this.setData({
          all_num: res.data.fight_num,
        });
      });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
    var that = this;
    //答题比赛id
    var quest_game_id = options.quest_game_id ? options.quest_game_id : 0;
    //用户数据
    var user = wx.getStorageSync("userInfo");

    //参数判断
    if (!user || !user.id || !user.grade_id || !quest_game_id) {
      wx.redirectTo({
        url: "../home/home",
      });
      return;
    }

    //保存数据
    that.setData({
      user: user,
      quest_game_id: quest_game_id,
      initiate_user_id: options.initiate_user_id || '',
      match_user_id: options.match_user_id || '',
      showBookName: user.show_book_flag == 1
    });

    //获取标题名称
    that.getIndexTt();

    if(user){
      // 建立 WebSocket 连接
      socket = wx.connectSocket({
        url: setting.ws,
        header: {
          "content-type": "application/json",
        },
        success(res) {
          console.log("WebSocket 连接成功: ", res);
        },
        fail(err) {
          console.log("WebSocket 连接失败: ", err);
        },
      });
      // onOpen
      socket.onOpen(() => {
        console.log("打开 WebSocket 连接");
        socketOpen = true;
        //发送请求
        that.send();
        console.log(new Date());
      });
      // onError
      socket.onError((err) => {
        console.log("WebSocket 连接失败：", err);
        socketOpen = false;
      });
      // onClose
      socket.onClose((ret) => {
        console.log("断开 WebSocket 连接", ret);
        socketOpen = false;
        console.log(new Date());
      });
      //监听接收到的消息
      socket.onMessage((res) => {
        let msg = res.data;
        var getData = that.mycallback(msg);
        console.log("接收到的服务器消息", getData);
        that.geMessage(getData);
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},
  // 播放音频
  playVideo() {
    console.log('playVideo========')
    this.data.musicVideo = wx.createInnerAudioContext({
      useWebAudioImplement: true,
    });
    this.data.musicVideo.loop = true; // 循环
    this.data.musicVideo.src =
      "https://game.shuguos.com/upload/video/countdown.mp3";
    this.data.musicVideo.play(); // 播放
  },
  // 停止播放音频并释放
  stopVideo() {
    console.log('stopVideo========')
    if (this.data.musicVideo) {
      this.data.musicVideo.stop(); // 停止音频资源
    }
    // if (this.data.musicVideo) {
    //   this.data.musicVideo.destroy(); // 释放音频资源
    // }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.stopVideo();
    clearInterval(timer);
    socket.close();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
    var user=wx.getStorageSync("userInfo");
    var path='/pages/home/home?unitid='+user.unitid+'&unitid_copy='+user.unitid_copy + "&inviterId=" + wx.getStorageSync("userInfo").id;
    return {
      title: app.globalData.shareInfo[e.from].title,
      imageUrl: app.globalData.shareInfo[e.from].imageUrl,
      path: path,
      success: function(res) {
        // 转发成功
        console.log(11212);
      },
      fail: function(res) {
        // 转发失败
      }
    }
  },
});
